import * as ts from 'typescript'

interface Config {
  function?: string[]
  nodeEnv?: string
}

export default (config: Config = {}): ts.TransformerFactory<ts.Node> =>
  (context) =>
  (sourceFile) => {
    if (config.nodeEnv && !process.env.NODE_ENV?.match(new RegExp(config.nodeEnv))) {
      return sourceFile
    }

    const visitor: ts.Visitor = (node) => {
      if (ts.isExpressionStatement(node)) {
        const exp = node.expression
        if (
          ts.isCallExpression(exp) &&
          ts.isIdentifier(exp.expression) &&
          config.function?.some((f) => new RegExp(f).test(exp.expression.getText()))
        ) {
          return undefined
        }
      }
      return ts.visitEachChild(node, visitor, context)
    }

    return ts.visitNode(sourceFile, visitor)
  }
